<template>
  <div class="login_container">
    <div class="form">
      <!-- :rules 验证表单 -->
      <!-- rules: 表单验证 -->
      <div class="form-title">
        <span>注册</span>
        <router-link to="/login">
          <el-link type="primary">点击登录</el-link>
        </router-link>
      </div>
      <el-form ref="formRef" class="login_form" :model="form" :rules="rules" size="large">
        <!-- 用户名 -->
        <!-- prop 指定校验规则 -->
        <el-form-item prop="nickName">
          <el-input placeholder="昵称" v-model="form.nickName"> </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="form.password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            placeholder="重复密码"
            v-model="form.confirmPassword"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            placeholder="邮箱（可选）后续可用作登录账号"
            v-model="form.email"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            placeholder="手机号（可选）后续可用作登录账号"
            v-model="form.phone"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            placeholder="请输入验证码"
            v-model="form.code"
            style="width: 63%"
          ></el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="submit">注册账号</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

  <!-- 注册结果弹出框 -->
  <el-dialog v-model="dialogVisible" title="注册结果" width="500" :before-close="void">
    <div class="result" style="">
      <h2 class="title" style="">
        <template v-if="result.status">
          <CircleCheck style="width: 3rem; color: #67c23a; margin-right: 10px" />注册成功
        </template>
        <template v-else>
          <CircleClose style="width: 3rem; color: #f56c6c; margin-right: 10px" />注册失败
        </template>
      </h2>
      <el-text v-if="!result.status" class="mx-1" size="large" type="info">
        {{ result.message }}
      </el-text>
      <div class="message" v-if="result.status">
        <span>您的帐号是</span>
        <span class="primary">
          {{ result.username || "888888" }}
        </span>
        <el-text class="mx-1" size="large" type="info">
          还可以使用邮箱或者手机号登陆哦
        </el-text>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="!result.status">重新注册</el-button>
        <el-button type="primary" @click="router.push('/login')"> 去登录 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/user';
import { ElMessage, ElNotification, useRestoreActive, type FormInstance, ElLoading } from 'element-plus';
import { ref, reactive, getCurrentInstance } from 'vue';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';

import Login from '@/api/login'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const ruleFormRef = ref<FormInstance>()

const form = reactive({
  nickName: "",
  password: "",
  confirmPassword: "",
  phone: '',
  email: '',
  code: '',
  uuid: ''
})

const dialogVisible = ref(false)
const isLoading = ref(false)

// const loading = ElLoading.service({
//     lock: true,
//     text: 'Loading',
//     background: 'rgba(0, 0, 0, 0.7)',
// })

const result = reactive({
  status: true,
  username: '',
  message: '' // 邮箱或手机号已经被注册
})

const handleClose = (evt) => {
  console.log(evt);

}

const codeUrl = ref('')

const submit = () => {

  proxy.$refs.formRef.validate((valid: any) => {
    if (!valid) {
     return ElMessage.warning('验证失败！')
    }
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    // isLoading.value = true
    Login.register(form).then((res) => {
      result.status = true
      result.message = res.message
      loading.close()
      // if (!res.status) {
      //   getCode()
      //   return ElMessage.error(res.message)
      // }
      result.username = res.data
      // isLoading.value = false
      dialogVisible.value = true
    }).catch(err => {
      console.log(err);
      loading.close()
      getCode()
    })
  })

}

const reset = () => {
  proxy.$refs.formRef.resetFields()
}

const getCode = async () => {
  const {data: {img, uuid}} = await Login.getCodeImage()
  codeUrl.value = "data:image/gif;base64," + img
  form.uuid = uuid
}

getCode()

const validatePass = (rule: any, value: any, callback: any) => {
  const regex = /^\w{8,18}$/
  if (!regex.test(value)) {
    callback(new Error('密码由数字、字母、下划线组成'))
  } else {
    callback()
  }
}
// const validatePass2 = (rule: any, value: any, callback: any) => {
//   if (value === '') {
//     callback(new Error('请再次输入密码'))
//   } else if (value !== form.rePass) {
//     callback(new Error("密码不一致"))
//   } else {
//     callback()
//   }
// }

const equalToPassword = (rule: any, value: any, callback: any) => {
  if (form.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const rules = reactive({
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 18, message: '长度在8到18个字符之间', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, trigger: "blur", message: "请再次输入您的密码" },
    { required: true, validator: equalToPassword, trigger: "blur" }
  ],
  phone: [
    { required: false, validator: (rule: any, value: any, callback: any) => {
      value == '' || /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
        .test(value) ? callback() : callback(new Error('手机号输入错误'))
    }, trigger: 'blur' },
  ],
  email: [
    { required: false, validator: (rule: any, value: any, callback: any) => {
      value == '' || /^\w+@\w+.\w+$/.test(value) ? callback() : callback(new Error('邮箱地址格式错误'))
    }, trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ]
})
</script>

<style scoped lang="less">
.login_container {
  background: linear-gradient(135deg, #17ead9, #6078ea);
  background-size: 300% 300%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  animation: gradient 5s ease infinite;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.form {
  background-color: #fff;
  padding: 50px;
  border-radius: 20px;
  width: 350px;
  box-sizing: content-box;
}

.form-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  align-items: baseline;

  & > span {
    font-size: xx-large;
  }
}
.login-code {
  width: 33%;
  height: 40px;
  // float: right;
  display: flex;
  align-items: center;
  margin-left: 4%;
  img {
    width: 100%;
    cursor: pointer;
    vertical-align: middle;
  }
}

.result {
  display: flex;
  flex-direction: column;
  .title {
    display: flex;
    align-items: center;
    padding-bottom: 1rem;
    justify-content: center;
  }

  .message {
    display: flex;
    flex-direction: column;
    align-items: center;
    .primary {
      color: #409eff;
      font-size: 1.5rem;
      font-weight: bold;
    }
  }
}
</style>
